﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace YunLuPos.DB.Utils
{
    public class Register
    {
        private static log4net.ILog logger = log4net.LogManager.GetLogger(typeof(Register));
        private static String licenseFile = Environment.CurrentDirectory + "/LINCENSE";
        /// <summary>
        /// 注册信息 根据机器码生成注册文件
        /// </summary>
        /// <returns></returns>
        public static bool register(RegInfo info)
        {
            if(info == null)
            {
                return false;
            }
            String stri = JsonConvert.SerializeObject(info);
            String encrypt = DESUtils.encrypt(stri);
            FileStream fs = null;
            try
            {
                fs = File.Create(licenseFile);
                byte[] bdata = Encoding.UTF8.GetBytes(encrypt);
                fs.Write(bdata, 0, bdata.Length);
                fs.Flush();
            }
            catch
            {
                return false;
            }
            finally
            {
                fs.Close();
            }
            return true;
        }

        /// <summary>
        /// 检查注册信息是否完善
        /// </summary>
        /// <returns></returns>
        public static RegInfo check(String mCode)
        {
            if (mCode == null)
                return null;
            try
            {
                if (File.Exists(licenseFile))
                {
                    String fileStr = File.ReadAllText(licenseFile);
                    if (fileStr != null)
                    {
                        RegInfo regInfo = null;
                        try
                        {
                            String jsonString = DESUtils.decrypt(fileStr);
                            var jSetting = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore };
                            regInfo = JsonConvert.DeserializeObject<RegInfo>(jsonString,jSetting);
                            if (mCode.Equals(regInfo.deviceNum))
                            {
                                return regInfo;
                            }
                        }
                        catch(Exception ex)
                        {
                            logger.Error(ex);
                        }
                        
                    }
                }
            }
            catch (Exception e)
            {
                logger.Error(e);
            }
            return null;
        }
    }
}
